package com.yangyu.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.yangyu.currency.Constant;
import com.yangyu.currency.StatusCode;
import com.yangyu.mapper.UserMapper;
import com.yangyu.message.BaseRsp;
import com.yangyu.message.user.LoginDto;
import com.yangyu.message.user.RegisterVo;
import com.yangyu.pojo.User;
import com.yangyu.shiro.AccountProfile;
import com.yangyu.util.JwtUtil;
import com.yangyu.util.RedisUtil;
import com.yangyu.util.ShiroUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper mapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;

    public BaseRsp getUserInfo(HttpServletResponse response) {
        AccountProfile userInfo = ShiroUtil.getProfile();
        if (userInfo == null) {
            return new BaseRsp(StatusCode.UserErrorCode.GET_USER_INFO_FAILED, "获取用户信息失败");
        }
        String jwt = jwtUtil.generateToken(userInfo.getId());

        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");
        return new BaseRsp(userInfo);
    }

    public BaseRsp getUsers(User user) {
        user = user == null ? new User() : user;
        List<User> users;
        try {
            users = mapper.getUsers(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseRsp(StatusCode.DB_ERROR, "dbError | get users failed");
        }
        return new BaseRsp(users);
    }

    public BaseRsp getUserById(User user) {
        if (user == null) {
            return new BaseRsp(StatusCode.PARAMS_ERROR, "user is empty");
        }
        User userById;
        try {
            userById = mapper.getUserById(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseRsp(StatusCode.DB_ERROR, "dbError | get userById failed");
        }
        return new BaseRsp(userById);
    }

    public BaseRsp editUser(User user) {
        if (user == null) {
            return new BaseRsp(StatusCode.PARAMS_ERROR, "user is empty");
        }
        if (!StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(SecureUtil.md5(user.getPassword()));
        }
        try {
            mapper.editUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseRsp(StatusCode.DB_ERROR, "dbError | edit user failed");
        }
        return new BaseRsp();
    }

    /**
     * 注册用户
     *
     * @param user 用户
     * @return 成功
     */
    public BaseRsp addUser(RegisterVo user) {
        Object code = redisUtil.get(Constant.Redis.VERIFICATION_CODE + user.getEmail());

        if (code == null || (int)code != user.getCheckCode()) {
            return new BaseRsp(StatusCode.UserErrorCode.CODE_ERROR, "验证码错误，请重试");
        }

        List<User> users;
        users = mapper.checkUserName(user.getUserName());
        if (!CollectionUtils.isEmpty(users)) {
            return new BaseRsp(StatusCode.UserErrorCode.USERNAME_ALREADY_EXISTS, "用户名已存在，换一个试试吧");
        }
        users = mapper.checkEmail(user.getEmail());
        if (!CollectionUtils.isEmpty(users)) {
            return new BaseRsp(StatusCode.UserErrorCode.EMAIL_REGISTERED, "邮箱已被注册");
        }

        user.setPassword(SecureUtil.md5(user.getPassword()));
        try {
            mapper.addUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseRsp(StatusCode.DB_ERROR, "dbError | add user failed");
        }
        return new BaseRsp();
    }

    public BaseRsp deleteUser(User user) {
        if (user == null) {
            return new BaseRsp(StatusCode.PARAMS_ERROR, "user is empty");
        }
        try {
            mapper.deleteUser(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseRsp(StatusCode.DB_ERROR, "dbError | delete user failed");
        }
        return new BaseRsp();
    }

    public User getById(long userId) {
        User user;
        try {
            user = mapper.getUserById(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return user;
    }

    public AccountProfile login(LoginDto dto, HttpServletResponse response) {
        User user;
        try {
            user = mapper.getPwdByEmail(dto.getEmail());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        Assert.notNull(user, "账户或者密码错误");
        Assert.isTrue(SecureUtil.md5(dto.getPassword()).equals(user.getPassword()), "账户或者密码错误");

        String jwt = jwtUtil.generateToken(user.getId());

        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");
        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user, profile);
        return profile;
    }

}
